package app.handler;

import app.vo.ResultResponse;
import app.utils.RedisTemplateUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler, ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private ResultResponse resultResponse;
    @Autowired
    private RedisTemplateUtils redisTemplateUtils;

    //身份验证成功处理程序
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //设置状态码
        resultResponse.setCode(200);
        //设置状态提示
        resultResponse.setMessage("登录成功");
        redisTemplateUtils.del();
        ResultResponse resultResponse = new ResultResponse(this.resultResponse.getCode(), this.resultResponse.getMessage(), this.resultResponse.getState(), this.resultResponse.getData());
        //设置编码
        httpServletResponse.setCharacterEncoding("UTF-8");
        //json格式返回
        httpServletResponse.getWriter().write(JSON.toJSONString(resultResponse));
    }

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        //获取用户输入的用户名
        User user = (User) event.getAuthentication().getPrincipal();
        redisTemplateUtils.del(user.getUsername()+"Frequency");
        redisTemplateUtils.del("my-redis-cache2::2");
    }
}
